using System;

namespace Tail
{
	/// <summary>
	/// Summary description for CommandParser.
	/// </summary>
	public class CommandParser
	{

		

		public static System.Collections.ArrayList getBaseVerifiers(){
			System.Collections.ArrayList verifiers = new System.Collections.ArrayList();

			// Add -f <lines> <file>
			Verifier v = new StringVerifier("-f","f");
			verifiers.Add(v);
			v.setNextVerifier(new IntegerVerifier("lines"));
			v = v.getNextVerifier();
			v.setNextVerifier(new StringVerifier("*","file"));

			// Add <lines> <file>
			v = new IntegerVerifier("lines");
			verifiers.Add(v);
			v.setNextVerifier(new StringVerifier("*","file"));

			// Add -f <file>
			v = new StringVerifier("-f","f");
			v.setNextVerifier(new StringVerifier("*","file"));
			verifiers.Add(v);

			// Add <file>
			verifiers.Add(new StringVerifier("*","file"));
			return verifiers;
		}

		private CommandParser()
		{
			
		}

		public static System.Collections.Hashtable parse(String[] args){
			System.Collections.ArrayList verifiers = getBaseVerifiers();
			System.Collections.Hashtable hash = null;
			bool found = false;
			foreach (Verifier verifier in verifiers){
				hash = new System.Collections.Hashtable();
				int level = 1;
				if (verifyVerifier(verifier,hash,args,level))
				{
					found = true;//Console.WriteLine("Found");
					break;
				}
			}
			if (found)
				return hash;
			else
				return null;
		}

		private static bool verifyVerifier(Verifier verifier,System.Collections.Hashtable hash, String[] args, int level){
			//Console.WriteLine(level + " : " + verifier.key);
			bool result = verifier.verify(args[level],hash);
			if (result && verifier.getNextVerifier()!=null)
			{
				level++;
				if (level<args.Length)
					result = result & verifyVerifier(verifier.getNextVerifier(),hash,args,level);
				else
					result = false;
			}
			//Console.WriteLine(level  + " : " + result);
			return result;
		}
	}
}
